package com.example.javaairportflightanalysis.comparator;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;

/**
 * @author shen
 * 按照时间排序
 */
public class GenericComparator<T> implements Comparator<T> {

    @Override
    public int compare(T vo1, T vo2) {

        Class<?> clazz = vo1.getClass();

        Field dtimeField = null;
        try {
        dtimeField = clazz.getDeclaredField("dtime");
        dtimeField.setAccessible(true);
        String dtime1 = null;
        dtime1 = (String) dtimeField.get(vo1);
        String dtime2 = (String) dtimeField.get(vo2);
        // 定义日期时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date date1 = dateFormat.parse(dtime1);
        Date date2 = dateFormat.parse(dtime2);
        return date1.compareTo(date2);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        // 如果解析失败，返回0表示相等
        return 0;
    }
    }

